package com.one.consumer.order.presenter;

import android.content.Context;

import com.google.gson.Gson;
import com.one.common.common.order.AddMaterialItem;
import com.one.common.common.order.MaterialItem;
import com.one.common.common.order.MaterialStateItem;
import com.one.common.config.CMemoryData;
import com.one.common.model.bean.PayWXBean;
import com.one.common.model.bean.UserInfoBean;
import com.one.common.model.extra.DefaultExtra;
import com.one.common.model.http.callback.ObserverOnResultListener;
import com.one.common.presenter.BaseApiPresenter;
import com.one.common.utils.PayUtils;
import com.one.common.utils.Toaster;
import com.one.common.view.base.BaseActivity;
import com.one.consumer.order.model.OrderModel;
import com.one.consumer.order.model.item.OrderDetailItem;
import com.one.consumer.order.ui.OrderDetailView;
import com.one.consumer.reserve.model.bean.YouhuijuanResaultBean;
import com.one.consumer.reserve.ui.activity.YouhuijuanListActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author ：zhulunjun
 * email  ：zhulunjun@qq.com
 * date   ：2018/10/31 11:56 PM
 * description ：
 **/
public class OrderDetailPresenter extends BaseApiPresenter<OrderDetailView, OrderModel> {
    private DefaultExtra extra;

    private double total;

    public OrderDetailPresenter(OrderDetailView mView, Context mContext) {
        super(mView, mContext, new OrderModel((BaseActivity) mContext));
    }

    @Override
    public void onCreate() {
        super.onCreate();
        extra = (DefaultExtra) mActivity.getIntent().getSerializableExtra(DefaultExtra.getExtraName());

    }

    private OrderDetailItem orderDetailItem;

    /**
     * 获取详情 detail
     */
    private ArrayList<Object> loadDate = new ArrayList<>();

    public void getOrderDetail() {
        if (extra != null) {
            mModel.orderDetail(extra.getStr(), new ObserverOnResultListener<OrderDetailItem>() {
                @Override
                public void onResult(OrderDetailItem orderDetailBean) {
                    if (mView != null) {
                        // 先添加详情
                        loadDate.clear();
                        loadDate.add(orderDetailBean);
                        // 维修项
                        addMaterialData(getAddMaterials(orderDetailBean.getMaintailOrderMaterialBeans()));
                        //优惠券
                        addYouhuijuanData(orderDetailBean.getCoupon().getMoney());
                        mView.loadSuccess(loadDate);
                        // 按钮状态
                        mView.setOrderDetail(orderDetailBean);
                        OrderDetailPresenter.this.orderDetailItem = orderDetailBean;
                    }

                }
            });
        }
    }


    /**
     * 获取有状态的材料列表
     */
    private List<AddMaterialItem> getAddMaterials(List<MaterialItem> data) {
        List<AddMaterialItem> result = new ArrayList<>();
        for (MaterialItem item : data) {
            if (item.getPrice() > 0) {
                result.add(new AddMaterialItem(item, false));
            } else {
                result.add(new AddMaterialItem(item, true));
            }
        }

        return result;
    }

    /**
     * 添加材料数据
     */
    private void addMaterialData(List<AddMaterialItem> datas) {
        if (mView != null) {
            List<AddMaterialItem> payData = new ArrayList<>();
            List<AddMaterialItem> freeData = new ArrayList<>();
            int total = 0;
            for (AddMaterialItem item : datas) {
                if (item.isFree()) {
                    freeData.add(item);
                } else {
                    payData.add(item);
                }
                total += (item.getNum() * item.getPrice());
            }
            if (payData.size() > 0) {
                loadDate.add(new MaterialStateItem(false));
                for (AddMaterialItem item : payData) {
                    loadDate.add(item);
                }
            }
            if (freeData.size() > 0) {
                loadDate.add(new MaterialStateItem(true));
                for (AddMaterialItem item : freeData) {
                    loadDate.add(item);
                }
            }
            if (total > 0) {
                loadDate.add(new AddMaterialItem(total));
                this.total = total;
            }

        }
    }


    /**
     * 添加优惠券
     */
    private void addYouhuijuanData(double total) {
        if (mView != null) {
            if(total != 0){
                AddMaterialItem addMaterialItem = new AddMaterialItem(total);
                addMaterialItem.setType(1);
                loadDate.add(addMaterialItem);
            }

            AddMaterialItem addMaterialItemTotal = new AddMaterialItem(this.total-total);
            addMaterialItemTotal.setType(2);
            loadDate.add(addMaterialItemTotal);
        }
    }


    /**
     * 取消订单
     */
    public void cancelOrder(String id) {
        mModel.cancelOrder(id, o -> {
            if (mView != null) {
                mView.refresh();
            }
        });
    }

    /**
     * 支付订单
     */
    public void payOrder(String id) {
        mModel.payOrder(id, new ObserverOnResultListener<PayWXBean>() {
            @Override
            public void onResult(PayWXBean o) {
                if (mView != null && o != null) {
                    PayUtils.getInstance(mActivity).wxPay(o)
                            .setIPayListener(new PayUtils.IPayListener() {
                                @Override
                                public void onSuccess() {
                                    mView.refresh();
                                    if(orderDetailItem!=null && orderDetailItem.getCoupon()!=null && orderDetailItem.getCoupon().getMoney()>0){
                                        userMyCoupon();
                                    }
                                }

                                @Override
                                public void onFail() {

                                }

                                @Override
                                public void onCancel() {
                                    Toaster.showLongToast("取消支付");
                                }
                            });
                }
            }
        });
    }

    private void userMyCoupon(){
        RequestParams params = new RequestParams("https://yinlong.yinweish.com/kmCouponController/v1.0/userMyCoupon");
        UserInfoBean bean = CMemoryData.getUserInfo();
        params.addBodyParameter("member_account",bean.getMember_account());
        params.addBodyParameter("member_id", bean.getMember_id()+"");
        params.addBodyParameter("member_token", bean.getMember_token());
        params.addBodyParameter("order_id", orderDetailItem.getOrder_id()+"");
        params.addBodyParameter("order_type", "1");
        params.addBodyParameter("flag", "2");
        params.addBodyParameter("id", orderDetailItem.getCoupon().getCoupon_id()+"");

        params.setCacheMaxAge(0);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.e("onSuccess "+result);
                Toaster.showLongToast("支付成功");
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }
            @Override
            public void onCancelled(Callback.CancelledException cex) {}
            @Override
            public void onFinished() {}
        });
    }

    /**
     * 确认订单
     */
    public void confirmOrder(String id) {
        mModel.confirmOrder(id, o -> {
            if (mView != null) {
//                    mView.refresh();
                //确认成功，直接跳转支付
                payOrder(id);
            }
        });
        mModel.confirmOrder(id, new ObserverOnResultListener<Object>() {

            @Override
            public void onResult(Object o) {
                if (mView != null) {
//                    mView.refresh();
                    //确认成功，直接跳转支付
                    payOrder(id);
                }
            }
        });
    }

    /**
     * 评价订单
     */
    public void evaluateOrder() {
        Map<String, String> params = new HashMap<>();
        mModel.evaluateOrder(params, o -> {
            if (mView != null) {

            }
        });
    }

    /**
     * 删除订单
     */
    public void deleteOrder(String id) {
        mModel.deleteOrder(id, o -> {
            if (mView != null) {
                mView.finishPage();
            }
        });
    }


}
